<template>
  <q-dialog v-model="alert" no-esc-dismiss no-route-dismiss no-backdrop-dismiss>
    <q-card class="dialog-card column">
      <q-card-section class="q-pb-none">
        <div class="row justify-between full-width" style="border-bottom: 1px solid #efefef;">
          <div class="text-subtitle1">{{title}}</div>

          <div class="right">
            <q-btn icon="clear" flat style="width: 40px;height: 40px;;margin-top:-8px" class="text-grey-8"  v-close-popup @click="close"/>
          </div>
        </div>
      </q-card-section>
      <q-card-section class="q-py-sm q-px-md col scroll-y">
        <div class="dialog-content column q-pt-sm">
          <q-form ref="myForm">
            <div v-for="(item,index) in from" :key="index" class="row q-py-sm text-weight-bold text-grey-9" >
              <div  class="text-right head" style="margin-top: 10px" :style="headStyle? headStyle : { width: '100px' }">
                {{item.title}}
              </div>
              <div class="col q-px-sm">
                <div v-if="item.type==='file'" class="column">
                  <div class="column items-start q-my-sm full-width" style="border:1px solid #efefef;border-radius: 5px;height:auto" v-if="String(state) === '2'">
                    <div class="row justify-between full-width" v-for="(row,idx) in result['result' + index]" :key="idx">
                      <q-img :src="assemblyPdtImg(row)" style="min-height: 200px"  class="col">
                        <template v-slot:error>
                          <img src="noimg.jpg" class="full-height">
                        </template>
                      </q-img>
                      <div class="col-1 column justify-center">
                       <q-btn style="width:40px;height:40px" size="12px" flat dense round icon="delete" @click="removeFile(row, index, idx)"/>
                      </div>
                    </div>
                  </div>

                  <q-uploader
                    style="max-width: 100%;width:400px"
                    :url="baseurl+ '/sys/upload/file'"
                    accept=".jpg, image/*"
                    field-name="file"
                    auto-upload
                    @failed="failed"
                    @uploaded="uploaded($event, index)"
                    @removed="removed($event, index)"
                    :label="item.uploadTitle"
                    :max-files="item.maxFiles"
                    :class="item.class"
                  >
                    <template v-slot:list="scope">
                      <q-list separator>
                        <q-item v-for="file in scope.files" :key="file.name">
                          <q-item-section>
                            <q-item-label class="full-width ellipsis">
                               文件名：{{ file.name }}
                            </q-item-label>

                            <q-item-label caption>
                              状态: {{ file.__status ==='uploaded'? '已上传': '闲置' }}
                            </q-item-label>

                            <q-item-label caption>
                              {{ file.__sizeLabel }} / {{ file.__progressLabel }}
                            </q-item-label>
                          </q-item-section>

                          <q-item-section v-if="file.__img" thumbnail class="gt-xs">
                            <img :src="file.__img.src" style="width: 180px;height: auto">
                          </q-item-section>

                          <q-item-section top side class="column justify-center">
                            <q-btn class="gt-xs" size="12px" flat dense round icon="delete" @click="scope.removeFile(file)"/>
                          </q-item-section>
                        </q-item>

                      </q-list>
                    </template>
                  </q-uploader>

                </div>
                <div v-else-if="['string','number'].includes(item.type)" class="row justify-start" style="height: 60px">
                  <q-input :type="item.type" lazy-rules :rules="item.rule" hint="" outlined v-model="result['result' + index]" dense :style="item.style" :class="item.class" :placeholder="item.placeholder || '请输入'+ item.title"/>
                  <span class="text-red q-pl-sm" v-if="item.required" style="margin-top: 10px">*</span>

                </div>
                <div v-else-if="['select'].includes(item.type)" class="row justify-start" style="height: 60px">
                  <q-select square dense outlined v-model="result['result' + index]" :options="item.options" :style="item.style" :class="item.class" style="height: 40px" />
                </div>
                <div v-else-if="['detail'].includes(item.type)" class="row">
                  <q-editor v-model="result['result' + index]" min-height="200px" :class="item.class" :style="item.style" />
                </div>
                <div v-else-if="['tree'].includes(item.type)">
                  <div class="column items-start q-my-sm full-width" style="border:1px solid #e3e3e3;border-radius: 5px;height:auto;min-height: 200px" >
<!--                    <q-chip outline square color="red" text-color="white" icon="done_all" :label="'选中：'+ label" v-if="!tickStrategy" />-->
                    <q-tree :nodes="batch" default-expand-all :selected.sync="selected" node-key="body" label-key="label"
                      @update:selected="updateTree" v-if="!tickStrategy"/>
                    <q-tree :nodes="batch" default-expand-all :expanded.sync="expanded" :ticked.sync="ticked" node-key="body"
                      label-key="label" :tick-strategy="tickStrategy" v-else-if="tickStrategy"/>
                  </div>
                </div>
                <div v-else-if="['label'].includes(item.type)">
                  <div style="margin-top: 10px;" class="q-pl-md">{{result['result' + index]}}</div>
                </div>
              </div>
            </div>
          </q-form>
        </div>

      </q-card-section>

      <q-card-actions align="right" class="q-px-md">
        <q-btn label="取消" color="black" v-close-popup @click="close"/>
        <q-btn label="保存" color="blue-8" @click="saveForm" v-if="String(state) === '1'"/>
        <q-btn label="修改保存" color="blue-8" @click="updateForm" v-else-if="!notSave"/>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script>
  import notify from "src/util/notify";
  import website from "src/const/website";
  import imageMixin from 'src/pages/mixins/ImageMixin'
  export default {
    name: "form",
    mixins: [imageMixin],
    props: ["alert", "from", "headStyle", "title", "updateData", "state", "tree", "batch", 'tickStrategy', 'notSave'],
    data(){
      return {
        selected: null,
        baseurl: website.baseURL,
        expanded: [],
        ticked: [],
        result: {
        },
        label: '未选择'
      }
    },
    methods:{
      submitHandler(callback){
        this.$refs.myForm.validate().then(success => {
          if (success) {
            let params = {}, state = true
            this.from.forEach((item1, index1) => {
              let field = item1.field || item1.title
              switch (item1.type) {
                case 'select':
                  if (field.indexOf(',') > -1) {
                    field.split(',').forEach((r, i) => {
                      if (this.result['result' + index1])
                        params[r] = (i === 0 ? this.result['result' + index1].label : this.result['result' + index1].value)
                      else
                        params[r] = ''
                    })
                  } else {
                    try {
                      params[field] = this.result['result' + index1].value
                    }catch (e) {
                      notify.warning("下拉选项必须选中内容！")
                      state = false;
                    }
                  }
                  break;
                case 'tree':
                  if(!this.tickStrategy) {
                    if (this.selected !== null) {
                      this.result['result' + index1] = this.selected
                    } else {
                      notify.warning("请选择节点")
                      state = false;
                    }
                  } else {
                    if (this.ticked.length > 0) {
                      this.result['result' + index1] = this.ticked.join(',')
                    } else {
                      notify.warning("请选择节点")
                    }
                  }
                default:
                  params[field] = this.result['result' + index1]
                  break;
              }
            })
            if(state) {
              callback(params)
            }
          } else {
            notify.warning('校验未通过！')
          }
        })
      },
      saveForm(){
        this.submitHandler((params)=>{
          this.$emit('submit', params)
        })
      },
      updateForm(){
        this.submitHandler((params)=>{
          this.$emit('submit', params)
        })
      },

      close(){
        this.$emit('close')
      },
      uploaded(info, index){
        if(info.xhr.response) {
          let response = JSON.parse(info.xhr.response)
          if(!Array.isArray(this.result['result' + index])){
            this.result['result' + index] = []
          }
          this.result['result' + index].push(response.data)
          // this.$emit('uploadedImage',response)
        }
      },
      removed(files, index){
        if(files[0].xhr.response) {
          let response = JSON.parse(files[0].xhr.response)
          if(!Array.isArray(this.result['result' + index])){
            this.result['result' + index] = JSON.parse(this.result['result' + index])
          }
          this.result['result' + index] = this.result['result' + index].filter(r=> r!== response.data)
          // this.$emit('removedImage', response)
        }
      },
      removeFile(file, index, idx){
        this.$set(this.result, 'result'+ index, this.result['result'+ index].filter((r,i)=>i!==idx))
        // this.$emit('removedImage', file)
      },
      failed(info){
        notify.warning('上传失败，上传信息：' + info.xhr)
      },
      updateState(updateData) {
        let result = {}
        // 数据初始化
        this.from.map((item,i) => {
          if(updateData.hasOwnProperty(item.field))
            switch (item.type) {
              case 'select':
                result['result' + i] = item.options.find(r=> r.value === updateData[item.field])
                break;
              case 'file':
                let array = []
                try{
                  array = JSON.parse(updateData[item.field])
                } catch (e) {
                  array = updateData[item.field].split(',')
                }
                result['result' + i] = array
                break
              case 'tree':

                if(this.tickStrategy){
                  this.ticked =  updateData[item.field].split(',')
                }else{
                  this.selected = updateData[item.field]
                }
                break;
              default:
                result['result' + i] = updateData[item.field]
                break;
            }
          return item
        })
        this.result = result
        // console.log(updateData)
      },
      updateTree(target){
        let tree = this.tree
        if(this.selected === 0){
          this.label =  '根节点'
        }else if(this.selected){
          tree.some(r => {
            if(r.id = target){
              this.label = r.name;
              return true
            }
            return false
          })
        }
      }
    },
    watch:{
      alert:function (val) {
        if(val && String(this.state) === '1') {
          let result = {}
          this.from.forEach((item, index) => {
            switch (item.type) {
              case 'select':
                if(item.options.length>0) {
                  result['result' + index] = item.options[0]
                }
                break;
              default:
                result['result' + index] = ''
                break;
            }
          })

          this.result = result
        }
      }
    },
    created() {
      this.$bus.$on('updateState', this.updateState)
    },
    beforeDestroy() {
      this.$bus.$off('updateState', this.updateState)
    }
  }
</script>

<style scoped>
  .dialog-card{
    width: 60vw;
    max-width: 60vw;
    height: 80vh;
  }
  .dialog-content{
    /*border-top:1px solid #999;*/
    /*border-radius: 5px;*/
  }
</style>
